﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

public class SCResampler : IStreamCapture {

    private IntPtr resampler;
    private ResampleData resampleData = new ResampleData();
    public SCResampler()
    {
        if (SCInstance.Instance == null)
            new GameObject("SCInstance").AddComponent<SCInstance>().Init();
        resampler = CreateResampler();
    }

    public bool Open(AudioStream srcas, AudioStream destas)
    {
        if (resampler == IntPtr.Zero) return false;
        if (OpenResampler(resampler, srcas, destas) != 0) return false;
        return true;
    }

    public ResampleData Resample(Frame frame)
    {
        if (resampler == IntPtr.Zero) return null;
        IntPtr ptr = Resample(resampler, frame.ptr);
        if (ptr == IntPtr.Zero) return null;
        ConvertResampleData(ref resampleData, ptr);
        return resampleData;
    }

    public void Close()
    {
        if (resampler == IntPtr.Zero) return;
        CloseResampler(resampler);
    }

    public void Release()
    {
        if (resampler == IntPtr.Zero) return;
        DeleteResampler(resampler);
        resampler = IntPtr.Zero;
    }

    ~SCResampler()
    {
        Release();
    }

}
